package com.example.sse.controller;

import com.example.sse.MessageVO;
import com.example.sse.SseEmitterServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/sse")
@CrossOrigin
public class SseController {

    @GetMapping(path = "/test1", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter test1() {
        SseEmitter emitter = new SseEmitter();
        // 注册事件监听
        eventListener(emitter);
        // 异步返回
        String text = """
       
                故人西辞黄鹤楼，烟花三月下扬州。
                孤帆远影碧空尽，唯见长江天际流。
                """;
        CompletableFuture.runAsync(() -> textGenerator(emitter, text));
        return emitter;
    }

    /**
     * 监听事件
     *
     * @param emitter emitter
     */
    private void eventListener(SseEmitter emitter) {
        emitter.onCompletion(() -> System.out.println("emitter completed"));
        emitter.onError(throwable -> System.out.println("emitter error"));
        emitter.onTimeout(() -> System.out.println("emitter timeout"));
    }

    /**
     * 模拟文字一个一个输出
     *
     * @param emitter emitter
     */
    private void textGenerator(SseEmitter emitter, String text) {
        int length = text.length();
        try {
            for (int i = 0; i < length; i++) {
                String word = String.valueOf(text.charAt(i));
                emitter.send(word);
                Thread.sleep(233);
                if (i == length - 1) {
                    emitter.complete();
                }
            }
        } catch (Exception e) {
            emitter.completeWithError(e);
            e.printStackTrace();
        }
    }





    @Autowired
    SseEmitterServer sseEmitterServer;


    @GetMapping(value = "/connect/{userCode}/{userId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @CrossOrigin
    public SseEmitter generateStreamsAsString(@PathVariable("userCode") String userCode, @PathVariable("userId") String userId) {
        return sseEmitterServer.connect(userCode, userId);
    }

    @GetMapping(value = "/close/{userCode}/{userId}")
    public void close(@PathVariable("userCode") String userCode,@PathVariable("userId") String userId ) {
        sseEmitterServer.complete(userCode, userId);
    }


//    @Autowired
//    SseInfoService  sseInfoService;
    private void handlerMessageInform() {
        ConcurrentHashMap<String, Map<String, SseEmitter>> sessionPool = SseEmitterServer.getSseEmitterPool();
        for (Map.Entry<String, Map<String, SseEmitter>> entry : sessionPool.entrySet()) {
            // 封装消息
//            MessageVO<List<MessageNotificationVO>> messageVO = new MessageVO();
//            messageVO.setTopic(TopicTypeEnum.MESSAGE_INFORM.getTopic());
//            messageVO.setData(messageService.getMessageList(request));
//            // 推送消息
//            sseEmitterServer.sendMessage(entry.getKey(), messageVO);
        }
    }



}
